<template>
  <div class="chart-container demo-spin-col">
    <h1 class="title">处理器使用率</h1>
    <div
      :id="myChartOneId"
      class="default-chart"
    >
    </div>
    <div class="table-box">
      <table
        class="table table-0"
        v-show="!loadingShow"
      >
        <tr>
          <th></th>
          <th></th>
          <th>最新</th>
          <th>最小</th>
          <th>平均</th>
          <th>最大</th>
        </tr>
      </table>
      <div class="seamless-box">
        <vue-seamless
          :data="cpuArr"
          :class-option="classOption"
          v-show="isThisGuyShow"
        >
          <table class="table">
            <template v-for="item in cpuArr">
              <tr>
                <td><i
                    class="spot"
                    :style="{background: bgArr[Math.floor(Math.random() * bgArr.length + 1)-1]}"
                  ></i></td>
                <td>{{ item.title}}</td>
                <td>{{ item.lastvalue}}{{item.units}}</td>
                <td>{{ item.lastvalue}}{{item.units}}</td>
                <td>{{ item.lastvalue}}{{item.units}}</td>
                <td>{{ item.lastvalue}}{{item.units}}</td>
              </tr>
            </template>
          </table>
        </vue-seamless>
      </div>

    </div>
    <Spin
      fix
      v-if="loadingShow"
    >
      <Icon
        type="ios-loading"
        size=18
        class="demo-spin-icon-load"
      ></Icon>
      <div>Loading</div>
    </Spin>
  </div>
</template>

<script>
let echarts = require('echarts/lib/echarts')
// 引入折线图
require('echarts/lib/chart/line')
// 引入提示框和title组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
import VueSeamless from 'vue-seamless-scroll'
import { getColor, randomColors } from '../service/getColor.js'


export default {
  name: "LineChartOne",
  props: [
    'oneId',
    'hostId',
    'currentIndex',
    'currentItemIndex'
  ],
  data() {
    return {
      myChartOneId: 'myChartOne' + this.oneId,
      // width: '100%',
      // height: '100%',
      cpuArr: [],
      cpu: [],
      currentCpu: 0,
      currentCpuName: '',
      theChart: null,
      bgArr: ['#00a144', '#01a3e7', '#e70101', '#ccfe00', '#e300fe', '#0fd379', '##f67708', '#5d3b1c', '#CC00FF', '#483D8B', '#008B8B', '#F08080'],
      xAxisData: [],
      yAxisData: [],
      arrtitle: [],
      cpuVal: null,
      interval: null,
      options: {
        title: {
          show: false,
          text: '内存使用率',
          x: 'left',
          y: 'top',

          textStyle: {
            color: '#ffffff',
            fontStyle: 'bold',
            fontSize: 20,
            verticalAlign: 'bottom'
          }
        },
        //提示框
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(0,0,0,0.4)',  //鼠标移动到图上面时，背景色
          padding: 2,     //定义内边距
        },
        // 工具栏，内置有导出图片、数据视图、动态类型切换、数据区域缩放、重置五个工具。
        toolbox: {
          show: false,
          //toolbox的配置项
          feature: {
            //辅助线的开关
            mark: { show: true },
            //数据视图
            dataView: {
              show: true,
              readOnly: false
            },
            //动态类型切换
            magicType: {
              show: true,
              //line为折线图，bar为柱状图
              type: ['line', 'bar']
            },
            //配置项还原
            restore: { show: true },
            //将图标保存为图片
            saveAsImage: { show: true }
          }
        },
        //可计算特性
        calculable: true,
        xAxis: {
          type: 'category', //类别
          boundaryGap: false, //数值起始和结束两端空白策略
          data: [],
          scale: false,
          splitNumber: 20,
          //x轴的字体样式
          axisLabel: {
            show: true,
            rotate: 45,
            textStyle: {
              color: '#08a9ae',
              fontSize: '12'
            },
          },
          // 控制网格线是否显示
          splitLine: {
            show: true,
            //  改变轴线颜色
            lineStyle: {
              color: ['#21475d'],
              width: 1,
              type: 'solid'
            }
          },
          // x轴的颜色和宽度
          axisLine: {
            show: true, //隐藏坐标轴
            lineStyle: {
              color: '#eeeeee',
              width: 1,   //这里是坐标轴的宽度,可以去掉
            }
          },
          // 去除坐标轴上的刻度线
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '',
          min: function (value) {
            return 0
          },
          max: function (value) {
            return Math.ceil(value.max)
          },
          splitNumber: 5,
          axisLabel: {
            formatter: '{value}%',  //y轴刻度数值颜色
            show: true,
            textStyle: {
              color: '#263f6d'
            }
          },
          // y轴的颜色和宽度
          axisLine: {
            show: true,
            lineStyle: {
              color: '#263f6d',
              width: 1,   //这里是坐标轴的宽度
            }
          },
          splitLine: {
            show: false,
            //  改变轴线颜色
            lineStyle: {
              color: ['#21475d'],
              width: 1,
              type: 'solid'
            }
          },
          // y轴的颜色和宽度
          axisLine: {
            show: true,
            lineStyle: {
              color: '#eeeeee',
              width: 1,   //这里是坐标轴的宽度
            }
          },
        },
        grid: { //控制图的大小
          top: 10,
          x: 50,
          x2: 30,
          y2: 30
        },
        series: [
          // {
          //   name:'',
          //   type:'line',
          //   stack: '总量',
          //   data:[]
          // }
        ]
        //   series: [{
        //     data: [],
        //     type: 'line',
        //     smooth: true,
        //     radius: '0',
        //     center: ['50%', '50%'],
        //     // showSymbol: false,
        //     symbolSize: 2,   //拐点圆的大小
        //     color: ['#0b97c2'],  //折线条的颜色
        //     itemStyle: {
        //       formatter: '{d}%',
        //       normal: {
        //         color: '#0b97c2',
        //         lineStyle: {
        //           color: '#0b97c2',
        //           formatter: '{c}%',
        //         }
        //       }
        //     },
        //     // areaStyle: {
        //     //   // 径向渐变，前三个参数分别是圆心 x, y 和半径，取值同线性渐变
        //     //   color: {
        //     //     type: 'linear',
        //     //     x: 0,
        //     //     y: 0,
        //     //     x2: 0,
        //     //     y2: 1,
        //     //     colorStops: [{
        //     //       offset: 0, color: '#19737a' // 0% 处的颜色
        //     //     }, {
        //     //       offset: 1, color: '#151515' // 100% 处的颜色
        //     //     }],
        //     //     globalCoord: false // 缺省为 false
        //     //   }
        //     // }
        //   }]
      },
      showPointsNum: 10, //图标上显示点和时间的个数
      loadingShow: true
    }
  },
  components: {
    VueSeamless
  },
  mounted() {
    var _this = this;
    // this.getCPUInfo();
    this.getCpu();
    setTimeout(() => {
      this.drawLine();
      window.addEventListener("resize", () => { this.theChart.resize(); });
    }, 0)
    this.interval = setInterval(() => {
      // this.getCPUInfo();
      this.getCpu();
    }, 60000)
    // this.getXData();
  },
  destroyed() {
    clearInterval(this.interval);
  },
  methods: {
    drawLine() {
      var _this = this;
      // 基于准备好的dom，初始化echarts实例
      this.theChart = echarts.init(document.getElementById(this.myChartOneId))
      // 绘制图表

      this.theChart.setOption(this.options);
    },
    // getXData() {
    //   this.$http.get('http://192.168.3.244:9080/api/cur_time', '').then(res => {
    //     let now = res.info;
    //     let oneHour = Date.parse(now) - 1 * 60 * 60 * 1000;
    //     oneHour = new Date(oneHour);
    //     let h = oneHour.getHours();
    //     let m = oneHour.getMinutes();
    //     for (let i = 60; i > 0; i--) {
    //       let x = Date.parse(now) - 1 * i * 60 * 1000;
    //       x = new Date(x);
    //       let h = x.getHours();
    //       let m = x.getMinutes();
    //       if (m<10){
    //         m = '0'+ m;
    //       }
    //       let str = h + ':' + m;
    //       this.xAxisData.push(str)
    //     }
    //     this.options.xAxis.data = this.xAxisData;
    //   })
    // },
    getDatas(obj) {
      var _this = this;
      let para = {
        "jsonrpc": "2.0",
        "method": "item.get",
        "params": {
          "output": "extend",
          "hostids": this.hostId,
          "search": obj,
          "sortfield": "name"
        },
        "auth": localStorage.getItem('auth'),
        "id": localStorage.getItem('currentId')
      }
      return new Promise((resolve, reject) => {
        _this.$http.post('/zabbix/api_jsonrpc.php', para).then(
          res => {
            resolve(res.result);
          },
          err => {
            reject('获取数据失败，请检查网络状况，或稍后刷新页面..')
          }
        )
      })
    },
    async getCpu() {
      var _this = this;
      try {
        var res = await this.getDatas({ "key_": "system.cpu" });
        console.log('lalalalal>>', res)
      } catch (err) {
        console.log(err)
      }
      //处理表格需要的数据
      res.forEach(v => {
        v.lastvalue = parseFloat(v.lastvalue).toFixed(2)
        let cpuNameTemp = '';
        if (v.name.indexOf('Processor') != -1) {
          v.title = v.name;
        } else {
          if (v.key_.indexOf('[') != -1) {
            cpuNameTemp = (v.key_.split(',')[1]).substring(0, (v.key_.split(',')[1]).length - 1);

          } else {
            cpuNameTemp = v.key_.substring(11);
          }
          v.title = 'CPU ' + cpuNameTemp + ' time';
        }
      })
      this.cpuArr = res;

      //处理图标需要的数据
      _this.cpu = [];
      let arr = [];
      // 过滤arr
      arr = res.filter(v => {
        return v.units == '%'
      })
      // console.log('ddjkhkdhj',arr)
      let total = 0;
      arr.forEach(v => {
        _this.cpu.push({
          name: v.key_,
          value: v.lastvalue
        })
        total += parseFloat(v.lastvalue);
      })
      let obj = { value: parseInt(total / arr.length), index: _this.currentItemIndex }
      _this.$store.commit("cpuTotalChange", obj);

      for (var i = 0; i < arr.length; i++) {
        _this.options.series.push({
          name: '',
          type: 'line',
          stack: 'value',
          data: [],
          smooth: true,
          radius: '0',
          center: ['50%', '50%'],
          // showSymbol: false,
          symbolSize: 2,   //拐点圆的大小
          color: this.bgArr[Math.floor(Math.random() * this.bgArr.length + 1) - 1],  //折线条的颜色
          itemStyle: {
            formatter: '{d}%',
            normal: {
              color: this.bgArr[Math.floor(Math.random() * this.bgArr.length + 1) - 1],
              lineStyle: {
                color: randomColors[i],
                formatter: '{c}%',
              }
            }
          }
          // ,
          // areaStyle: {
          //     // 径向渐变，前三个参数分别是圆心 x, y 和半径，取值同线性渐变
          //     color: {
          //       type: 'linear',
          //       x: 0,
          //       y: 0,
          //       x2: 0,
          //       y2: 1,
          //       colorStops: [{
          //         offset: 0, color: randomColors[i] // 0% 处的颜色
          //       }, {
          //         offset: 1, color: '#01b1a2' // 100% 处的颜色
          //       }],
          //       globalCoord: false // 缺省为 false
          //     }
          //   }
        })
      }
      for (var i = 0; i < _this.cpu.length; i++) {
        _this.currentCpu = _this.cpu[i].value;
        _this.currentCpuName = _this.cpu[i].name;
        _this.currentCpu = parseFloat(_this.currentCpu).toFixed(2);
        console.log(_this.currentCpu);

        if (_this.options.series[i].data.length < _this.showPointsNum) {
          _this.options.series[i].data.push(this.currentCpu);
          _this.options.series[i].name = this.currentCpuName;
        } else {
          _this.options.series[i].data.shift();
          _this.options.series[i].data.push(_this.currentCpu);
        }

        //获取数组内最大值 设置y轴最大值
        var min = _this.options.series[i].data.sort()[0]
        var max = _this.options.series[i].data.sort().reverse()[0];
        // _this.options.yAxis.max({min:'0',max:max});
        console.log('******----->', max, min)
        _this.options.yAxis.max({ min: min, max: max });
      }
      var date = new Date()
      var h = date.getHours();
      var m = date.getMinutes();
      if (m < 10) {
        m = '0' + m;
      }
      var time = h + ":" + m;
      if (_this.options.xAxis.data.length < _this.showPointsNum) {
        _this.options.xAxis.data.push(time)
      } else {
        _this.options.xAxis.data.shift();
        _this.options.xAxis.data.push(time)
      }
      _this.theChart.setOption(_this.options);

      this.loadingShow = false;
    }
    // getCPUInfo() {
    //   let para = {
    //     "jsonrpc": "2.0",
    //     "method": "item.get",
    //     "params": {
    //       "output": "extend",
    //       "hostids": this.hostId,
    //       "search": {
    //         "key_": "system.cpu"
    //       },
    //       "sortfield": "name"
    //     },
    //     "auth": localStorage.getItem('auth'),
    //     "id": localStorage.getItem('currentId')
    //   }
    //   this.$http.post('http://203.2.164.112:90/zabbix/api_jsonrpc.php', para).then(res => {
    //     // 处理cpu名称
    //     console.log('lalalala>>>',res.result);
    //     res.result.forEach(v => {
    //       let cpuNameTemp = '';
    //       if (v.name.indexOf('Processor') != -1) {
    //         v.title = v.name;
    //       } else {
    //         if (v.key_.indexOf('[') != -1) {
    //           cpuNameTemp = (v.key_.split(',')[1]).substring(0, (v.key_.split(',')[1]).length - 1);

    //         } else {
    //           cpuNameTemp = v.key_.substring(11);
    //         }
    //         v.title = 'CPU ' + cpuNameTemp + ' time';
    //       }
    //     })
    //     this.cpuArr = res.result;
    //   },err=>{
    //     console.log(err)
    //   })
    // },
  },
  computed: {
    classOption: function () {
      return {
        step: 0.2,
        limitMoveNum: 5
      }
    },
    isThisGuyShow: function () {
      return this.currentIndex == this.currentItemIndex
    }
  }
}
</script>

<style scoped lang="scss">
.chart-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  color: #ffffff;
  width: 100%;
  height: 50%;
  border: 28px solid;
  border-top: 20px solid;
  // border-right: 28px solid;
  border-left: 5px solid;
  /*border-bottom: 20px solid;*/
  background: transparent;
  border-image: url("../assets/images/21.png") 28 fill repeat;
  position: relative;
  overflow: hidden;

  .title {
    color: #fff;
    width: 20px;
    font-size: 16px;
    word-wrap: break-word;
    position: absolute;
    left: 10px;
    top: 10px;
  }

  .default-chart {
    width: 100%;
    padding-left: 30px;
    height: 170px;
    // position: absolute;
    // left: 30px;
    // top: 0;
  }

  .table-box {
    table {
      flex: 1;
      // height: 126px;
      width: 100%;
      padding: 0 0 0 30px;
      // position: absolute;
      // top: 178px;
      // right: 0;
      color: #08a9ae;
      text-align: center;
      line-height: 12px;

      &.table-0 {
        height: 20px;
        /*position: fixed;*/
      }

      tr {
        th,
        td {
          width: 60px;
          text-align: center;
          display: inline-block;

          &:first-child {
            width: 14px;
          }

          &:nth-child(2) {
            width: 120px;
            text-align: left;
          }

          .spot {
            width: 9px;
            height: 9px;
            display: inline-block;
            background: #08a9ae;
            margin-right: 5px;
          }
        }
      }
    }

    .seamless-box {
      height: 60px;
      overflow: hidden;
    }
  }
}
/*加载中的作用范围*/
.demo-spin-col {
  position: relative;
}
.ivu-spin-fix {
  background-color: rgba(0, 0, 0, 0.2);
}
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
</style>
